package cn.fintecher.gis.geoserver;

import cn.fintecher.gis.config.PostGISDataStoreConfig;
import cn.fintecher.gis.model.ParsingShpResults;
import it.geosolutions.geoserver.rest.GeoServerRESTManager;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.decoder.RESTDataStore;
import it.geosolutions.geoserver.rest.decoder.RESTLayer;
import it.geosolutions.geoserver.rest.decoder.RESTStyleList;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import it.geosolutions.geoserver.rest.encoder.GSLayerEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSPostGISDatastoreEncoder;
import it.geosolutions.geoserver.rest.encoder.feature.GSFeatureTypeEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ChenChang on 2018/12/7.
 */
@Service
public class GeoManagerService {
    @Value("${geo.username}")
    private String username;
    @Value("${geo.password}")
    private String password;
    @Value("${geo.url}")
    private String url;
    //    @Value("${geo.layerSpace}")
//    private String layerSpace;
    @Value("${geo.storeName}")
    private String storeName;

    @Autowired
    private PostGISDataStoreConfig postGISDataStoreConfig;

//    public String getLayerSpace() {
//        return layerSpace;
//    }

    /**
     * 发布图层
     *
     * @param tableName
     * @return
     * @throws MalformedURLException
     */
//    public ParsingShpResults releaseLayer(String tableName, String crs, List<String> styles) throws MalformedURLException {
//
//        return releaseLayer(tableName, crs, styles, this.layerSpace);
//    }

    public ParsingShpResults releaseLayer(String tableName, String crs, List<String> styles, String workSpace) throws MalformedURLException {
        URL u = new URL(url);
        GeoServerRESTManager manager = new GeoServerRESTManager(u, username, password);
        GeoServerRESTPublisher publisher = manager.getPublisher();
        List<String> workspaces = manager.getReader().getWorkspaceNames();
        if (!workspaces.contains(workSpace)) {
            publisher.createWorkspace(workSpace);
        }
//        RESTStyle restStyle =RESTStyle.build("");
//        manager.getStyleManager().

        RESTDataStore restStore = manager.getReader().getDatastore(workSpace, storeName);

        if (restStore == null) {
            GSPostGISDatastoreEncoder store = new GSPostGISDatastoreEncoder(storeName);
            store.setHost(postGISDataStoreConfig.getHost());//设置url
            store.setPort(Integer.valueOf(postGISDataStoreConfig.getPort()));//设置端口
            store.setUser(postGISDataStoreConfig.getUsername());// 数据库的用户名
            store.setPassword(postGISDataStoreConfig.getPassword());// 数据库的密码
            store.setDatabase(postGISDataStoreConfig.getDatabase());// 那个数据库;
            store.setSchema(postGISDataStoreConfig.getSchema()); //当前先默认使用public这个schema
            store.setConnectionTimeout(20);// 超时设置
            store.setMaxConnections(20); // 最大连接数
            store.setMinConnections(1);     // 最小连接数
            store.setExposePrimaryKeys(true);
            manager.getStoreManager().create(workSpace, store);
        }

        RESTLayer layer = manager.getReader().getLayer(workSpace, tableName);
        if (layer == null) {
            GSFeatureTypeEncoder pds = new GSFeatureTypeEncoder();
            pds.setTitle(tableName);
            pds.setName(tableName);
            pds.setSRS("EPSG:4326");
//            if (StringUtils.equalsIgnoreCase(crs, "CGCS_2000_3_Degree_GK_Zone_37")) {
//                pds.setSRS("EPSG:4525");
//            } else {
//                pds.setSRS("EPSG:2361");
//            }

            GSLayerEncoder layerEncoder = new GSLayerEncoder();
            if (styles != null && !styles.isEmpty()) {
                layerEncoder.setDefaultStyle(styles.get(0));
                for (String style : styles) {
                    layerEncoder.addStyle(style);
                }
            }

            boolean publish = manager.getPublisher().publishDBLayer(workSpace, storeName, pds, layerEncoder);
            if (publish) {

                return new ParsingShpResults(true, "");
            } else {
                return new ParsingShpResults(false, "geo.error");
            }

        } else {
            return new ParsingShpResults(false, "geo.layer.existed");
        }

    }

    /**
     * 查询图层现有的样式
     *
     * @param tableName
     * @return
     * @throws MalformedURLException
     */
    public List<String> queryLayerStyles(String tableName, String workSpace) throws MalformedURLException {
        URL u = new URL(url);
        GeoServerRESTManager manager = new GeoServerRESTManager(u, username, password);
        GeoServerRESTPublisher publisher = manager.getPublisher();
        List<String> workspaces = manager.getReader().getWorkspaceNames();
        if (!workspaces.contains(workSpace)) {
            publisher.createWorkspace(workSpace);
        }
        RESTLayer layer = manager.getReader().getLayer(workSpace, tableName);
        if (layer == null) {
            throw new RuntimeException("图层未找到");
        }

        RESTStyleList list = layer.getStyles();
        List<String> lists = new ArrayList<>();
        for (NameLinkElem nameLinkElem : list) {
            lists.add(nameLinkElem.getName());
        }
        return lists;
    }

    /**
     * 修改图层
     *
     * @param tableName
     * @param styles
     * @throws MalformedURLException
     */
    public void changeLayerStyles(String tableName, List<String> styles, String workSpace) throws MalformedURLException {
        URL u = new URL(url);
        GeoServerRESTManager manager = new GeoServerRESTManager(u, username, password);
        GeoServerRESTPublisher publisher = manager.getPublisher();
        List<String> workspaces = manager.getReader().getWorkspaceNames();
        if (!workspaces.contains(workSpace)) {
            publisher.createWorkspace(workSpace);
        }
        RESTLayer layer = manager.getReader().getLayer(workSpace, tableName);
        if (layer == null) {
            throw new RuntimeException("图层未找到");
        }
        GSLayerEncoder layerEncoder = new GSLayerEncoder();

        if (styles != null && !styles.isEmpty()) {
            layerEncoder.setDefaultStyle(styles.get(0));
            for (String style : styles) {
                layerEncoder.addStyle(style);
            }
        }
        manager.getPublisher().configureLayer(workSpace, layer.getName(), layerEncoder);
    }

    public void releaseStyle(String styleName, String styleBody, String workSpace) throws MalformedURLException {
        URL u = new URL(url);
        GeoServerRESTManager manager = new GeoServerRESTManager(u, username, password);
        GeoServerRESTPublisher publisher = manager.getPublisher();
        List<String> workspaces = manager.getReader().getWorkspaceNames();
        if (!workspaces.contains(workSpace)) {
            publisher.createWorkspace(workSpace);
        }
        manager.getStyleManager().publishStyleInWorkspace(workSpace, styleBody, styleName);
//       for(manager.getReader().getLayers().getNames())

    }

    /**
     * 删除图层
     * @param layerName
     * @param workSpace
     * @throws MalformedURLException
     */
    public void deleteLayer(String layerName,String workSpace) throws MalformedURLException {
        URL u = new URL(url);
        GeoServerRESTManager manager = new GeoServerRESTManager(u, username, password);
        manager.getPublisher().removeLayer(workSpace, layerName);
    }

    /**
     * 删除默认空间图层
     * @param layerName
     * @throws MalformedURLException
     */
//    public void deleteLayer(String layerName,String layerSpace) throws MalformedURLException {
//        deleteLayer(layerName,layerSpace);
//    }


}
